<template>
  <div class="app-container">
    <el-tabs v-model="activeName">
      <el-tab-pane label="产品基本信息" name="product-base">
        <el-card class="box-card">
          <el-form ref="dataForm" :rules="baseRules" :model="product" label-width="80px">
            <el-form-item label="产品名称" prop="name">
              <el-input v-model="product.name" placeholder="请输入产品名称" maxlength="50"/>
            </el-form-item>
            <el-form-item label="所属类目" prop="categoryId">
              <el-cascader :options="categories" :props="{label:'name', value:'id', children:'children', expandTrigger: 'hover'}" v-model="product.categoryId" placeholder="选择产品类目" clearable @change="chooseCategory"/>
            </el-form-item>
            <el-form-item label="运费模板" prop="freightId">
              <el-select v-model="product.freightId" placeholder="选择运费模板" @change="chooseFreightTemplate">
                <el-option v-for="(item, index) in freightTemplates" :key="index" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="产品单位" prop="unit">
              <el-select v-model="product.unit" placeholder="请选择产品单位">
                <el-option v-for="(item, index) in units" :key="index" :label="item.name" :value="item.name"/>
              </el-select>
            </el-form-item>
            <el-form-item label="虚拟销量" prop="virtualSales">
              <el-input v-model.number="product.virtualSales" style="width:200px" placeholder="请输入产品虚拟销量" maxlength="50"/>
            </el-form-item>
            <el-form-item label="排序" prop="seq">
              <el-input v-model.number="product.seq" style="width:200px" placeholder="请输入产品排序" maxlength="50"/>
            </el-form-item>
            <el-form-item label="产品上架" prop="onShelf">
              <el-switch v-model="product.onShelf" active-color="#13ce66"/>
            </el-form-item>
            <el-form-item label="标签" prop="tag">
              <el-radio-group v-model="product.tag" size="medium">
                <el-radio :label="0">无</el-radio>
                <el-radio v-for="(tag,index) in tags" :key="index" :label="parseInt(tag.value)">{{ tag.name }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="产品封面" prop="cover">
              <uploader :file-list.sync="fileList" @success="uploadCoverSuccess" @remove="removeCoverSuccess"/>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="产品图片" name="product-imgs">
        <el-card class="box-card">
          <el-alert :closable="false" type="success" description="最多上传6张图片 图片大小建议 320 x 140像素"/>
          <br>
          <uploader :limit="6" :file-list.sync="imgs" @success="uploadImgsSuccess" @remove="removeImgsSuccess"/>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="产品详情" name="product-txt">
        <el-card class="box-card">
          <el-form :model="product.txt" label-width="80px">
            <el-form-item label="产品简介" prop="summary">
              <el-input v-model="product.txt.summary" type="textarea" rows="5"/>
            </el-form-item>
            <el-form-item label="产品详情" prop="remark">
              <editor :init="editorInit" v-model="product.txt.remark"/>
            </el-form-item>
          </el-form>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="产品参数" name="product-attr">
        <el-card class="box-card">
          <el-form ref="attrForm" :model="attr" :rules="attrRules" status-icon label-position="center" label-width="100px">
            <el-form-item label="参数名称" prop="name" style="float:left">
              <el-input v-model="attr.name" />
            </el-form-item>
            <el-form-item label="参数值" prop="data" style="float:left;margin-right:1em">
              <el-input v-model="attr.data" />
            </el-form-item>
          </el-form>
          <el-button :plain="true" type="primary" @click="addAttr">添加</el-button>
          <el-table :data="product.attrs" border>
            <el-table-column property="name" label="参数名称" />
            <el-table-column property="data" label="参数值" />
            <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button v-permission="['product:edit']" type="danger" size="mini" @click="deleteAttr(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="产品SKU" name="fourth">
        <el-card class="box-card">
          <el-table :data="product.speAttrs" row-key="name" border>
            <el-table-column property="name" label="规格名称" />
            <el-table-column property="seq" label="序号"/>
          </el-table>
        </el-card>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <h4>商品SKU详情</h4>
            <el-button :plain="true" type="primary" @click="skuBatchPriceDialogVisible = true">批量定价</el-button>
          </div>
          <el-table :data="product.skus" :span-method="skuTableSpanMethod" border style="width: 100%; margin-top: 20px">
            <el-table-column v-for="(item, index) in product.speAttrs" :key="index" :prop="'id_'+item.seq" :label="item.name"/>
            <el-table-column prop="price" label="现售价(元)">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.price" :precision="2" :min="0.00" :max="2147483647" size="small" />
              </template>
            </el-table-column>
            <el-table-column prop="vipPrice" label="VIP价(元)">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.vipPrice" :precision="2" :min="0.00" :max="2147483647" size="small" />
              </template>
            </el-table-column>
            <el-table-column prop="originalPrice" label="原价(元)">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.originalPrice" :precision="2" :min="0.00" :max="2147483647" size="small" />
              </template>
            </el-table-column>
            <el-table-column label="库存" prop="stock">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.stock" :precision="0" :min="0" :max="2147483647" size="small" />
              </template>
            </el-table-column>
          </el-table>

          <el-dialog :close-on-click-modal="false" :visible.sync="skuBatchPriceDialogVisible" title="批量定价">
            <el-form ref="skuBatchPriceForm" :model="skuBatchPriceForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
              <el-form-item label="现价(￥)" prop="price">
                <el-input-number v-model="skuBatchPriceForm.price" :precision="2" :min="0.00" :max="2147483647" size="small" />
              </el-form-item>
              <el-form-item label="VIP价格(￥)" prop="vipPrice">
                <el-input-number v-model="skuBatchPriceForm.vipPrice" :precision="2" :min="0.00" :max="2147483647" size="small" />
              </el-form-item>
              <el-form-item label="原价(￥)" prop="originalPrice">
                <el-input-number v-model="skuBatchPriceForm.originalPrice" :precision="2" :min="0.00" :max="2147483647" size="small" />
              </el-form-item>
              <el-form-item label="库存" prop="originalPrice">
                <el-input-number v-model="skuBatchPriceForm.stock" :min="0" :max="2147483647" size="small" />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="skuBatchPriceDialogVisible = false">取消</el-button>
              <el-button v-permission="['product:edit']" type="primary" @click="batchSetPrice">确定</el-button>
            </div>
          </el-dialog>
        </el-card>
      </el-tab-pane>
    </el-tabs>
    <div class="text-center" style="margin-top:1em">
      <el-button @click="handleCancel">取消</el-button>
      <el-button v-permission="['product:edit']" type="primary" @click="edit">更新商品</el-button>
    </div>
  </div>
</template>

<script>
import { CommonService, DictionaryService } from '@/api/CommonService'
import Editor from '@tinymce/tinymce-vue'
import Uploader from '@/components/Uploader'
import { Alert, Notify } from '@/utils/notify'
import { ProductService, CategoryService, FreightTemplateService } from '@/api/ProductService'

export default {
  name: 'ProductDetail',
  components: { Uploader, Editor },
  data() {
    return {
      activeName: 'product-base', fileList: [], imgs: [], editSpeAttrDialogVisible: false, spe: { seq: 0, name: '', data: '', parent: 0 },
      categories: [], freightTemplates: [], tags: [], units: [], attr: { name: '', data: '' }, speAttr: { name: '', data: undefined },
      product: { name: undefined, categoryId: undefined, freightId: undefined, unit: undefined, virtualSales: 0, onShelf: true, cover: undefined,
        imgs: [], txt: { summary: undefined, remark: undefined }, attrs: [], speAttrs: [], skus: [], tag: 0, seq: 0
      },
      categoryIds: [],
      skuBatchPriceDialogVisible: false,
      skuBatchPriceForm: {},
      baseRules: {
        name: [{ required: true, message: '产品名称不能为空!', trigger: 'blur' }],
        categoryId: [{ required: true, message: '请选择产品类型!', trigger: 'blur' }],
        freightId: [{ required: true, message: '请选择产品运费模板!', trigger: 'blur' }],
        unit: [{ required: true, message: '产品单位不能为空', trigger: 'blur' }],
        cover: [{ required: true, message: '请上传产品封面图片' }],
        virtualSales: [{ required: true, message: '请输入产品虚拟销量', trigger: 'blur' }, { type: 'number', message: '必须是整数!', trigger: 'blur' }],
        seq: [{ required: true, message: '请输入产品排序', trigger: 'blur' }, { type: 'number', message: '必须是整数!', trigger: 'blur' }]
      },
      attrRules: {
        name: [{ required: true, message: ' ', trigger: 'blur' }],
        data: [{ required: true, message: ' ', trigger: 'blur' }]
      },
      editorInit: {
        language: 'zh_CN',
        convert_urls: false, height: 300,
        plugins: ['advlist anchor autolink autosave code codesample directionality emoticons fullscreen hr image axupimgs imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image axupimgs charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          CommonService.uploadFile(formData).then(res => {
            success(res.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      }
    }
  },
  created() {
    this.loadProduct()
    this.loadCategory()
    this.loadFreightTemplate()
    this.loadUnits()
    this.loadTags()
  },
  methods: {
    loadProduct() {
      const productId = this.$route.query.productId
      ProductService.getProduct(productId).then(result => {
        this.product = result
        if (result.cover) {
          this.fileList.push({ url: result.url })
        }
        if (result.imgs) {
          result.imgs.forEach(img => {
            this.imgs.push({ url: img.url })
          })
        }
        if (result.speAttrs) {
          this.product.speAttrs.forEach(attr => {
            attr.children = attr.data
          })
        }
        this.loadSkuTable()
      })
    },
    loadCategory() {
      CategoryService.loadCategoryTree().then(result => {
        this.categories = result
      })
    },
    chooseCategory(value) {
      this.product.categoryId = value[value.length - 1]
    },
    loadFreightTemplate() {
      FreightTemplateService.getAllFreightTemplateNames().then(result => {
        this.freightTemplates = result
      })
    },
    chooseFreightTemplate(templateId) {
      this.product.freightId = templateId
    },
    loadUnits() {
      DictionaryService.listDictionaryByType('product_unit').then(result => {
        this.units = result
      })
    },
    loadTags() {
      DictionaryService.listDictionaryByType('product_tag').then(result => {
        this.tags = result
      })
    },
    uploadCoverSuccess(data) {
      this.product.cover = data.path
    },
    removeCoverSuccess() {
      this.product.cover = undefined
    },
    uploadImgsSuccess(data) {
      const count = this.product.imgs.length
      this.product.imgs[count] = { seq: count + 1, originalImg: data.path }
    },
    removeImgsSuccess(index) {
      this.product.imgs.splice(index, 1)
      this.product.imgs.forEach((item, seq) => {
        item.seq = seq + 1
      })
      console.log(this.product.imgs)
    },
    addAttr() {
      this.$refs['attrForm'].validate(valid => {
        if (valid) {
          const seq = this.product.attrs.length
          this.attr.seq = seq + 1
          this.product.attrs.push(this.attr)
          this.attr = { name: undefined, data: undefined }
        }
      })
    },
    deleteAttr(row) {
      const index = this.product.attrs.indexOf(row)
      this.product.attrs.splice(index, 1)
      this.product.attrs.forEach((attr, index) => {
        attr.seq = index + 1
      })
    },

    handleCancel: function() {
      this.$router.push({ path: '/product/list' })
    },
    edit: function() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          ProductService.editProduct(this.product).then(() => {
            Notify.success(this, '更新成功')
            this.$router.push({ path: '/product/list' })
          })
        } else {
          Alert.warn(this, '请填写完整信息!')
        }
      })
    },
    skuTableSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex < this.product.speAttrs.length) {
        let ji = 1
        for (let z = columnIndex + 1; z < this.product.speAttrs.length; z++) {
          ji = ji * this.product.speAttrs[z].data.length
        }
        if (rowIndex % ji === 0) {
          return {
            rowspan: ji,
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      } else {
        return {
          rowspan: 1,
          colspan: 1
        }
      }
    },
    loadSkuTable() {
      this.product.skus.forEach(sku => {
        const values = sku.speAttrValue.split(',')
        values.forEach((value, index) => {
          const speAttr = this.product.speAttrs[index]
          const jsonArray = speAttr.data
          jsonArray.forEach(json => {
            if (parseInt(json.seq) === parseInt(value)) {
              sku['id_' + speAttr.seq] = json.name
            }
          })
        })
      })
    },

    batchSetPrice() {
      this.product.skus.forEach(item => {
        item.price = this.skuBatchPriceForm.price
        item.vipPrice = this.skuBatchPriceForm.vipPrice
        item.originalPrice = this.skuBatchPriceForm.originalPrice
        item.stock = this.skuBatchPriceForm.stock
      })
      this.skuBatchPriceDialogVisible = false
    }
  }
}
</script>
